package com.coisshi.base.common.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.Data;

/**
 * 微信小程序工具类
 */
public class WechatMiniProgramUtils {

    private static final String CODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 根据小程序 code 换取 openId、sessionKey
     *
     * @param appId 小程序AppId
     * @param appSecret 小程序AppSecret
     * @param code 前端传过来的code
     * @return 返回 openId 和 sessionKey
     */
    public static Code2SessionResult code2Session(String appId, String appSecret, String code) {
        String url = String.format("%s?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                CODE2SESSION_URL, appId, appSecret, code);

        String response = HttpUtil.get(url);
        return JSONUtil.toBean(response, Code2SessionResult.class);
    }

    @Data
    public static class Code2SessionResult {
        private String openid;
        private String session_key;
        private String unionid;
        private Integer errcode;
        private String errmsg;
    }
}

